﻿// 麻省理工学院许可证
//
// 版权所有 (c) 2021-2023 zuohuaijun，大名科技（天津）有限公司  联系电话/微信：18020030720  QQ：515096995
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using Admin.NET.Application.Const;
using AlibabaCloud.TeaUtil.Models;
using COSXML.Network;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Tea;
using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;


namespace Admin.NET.Application.Service.TopSdk;

/// <summary>
/// 阿里云sdk
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class TopSdkService : IDynamicApiController, ITransient
{
    private readonly TopSdkOptions _topSdkOptions;
    public TopSdkService(IOptions<TopSdkOptions> topSdkOptions)
    {
        _topSdkOptions = topSdkOptions.Value;
    }
    /// <summary>
    /// 获取AccessToken
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    [ApiDescriptionSettings(Name = "GetAccessToken")]
    public async Task<GetAccessTokenResponse> GetAccessTokenAsync()
    {
        //string appKey = "dingxyxkpkzpcfutakbb";
        //string appSecret = "bkFBttSBrUQEFEshg61S0snsjq3VdV0EjwoHj9pVOuY-ZuMn1WlnZuWthB2X86UL";
        string appKey = _topSdkOptions.AppKey;
        string appSecret = _topSdkOptions.AppSecret;

        string url = $"https://oapi.dingtalk.com/gettoken?appkey={appKey}&appsecret={appSecret}";

        try
        {
            using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
            {
                HttpResponseMessage response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode(); // Ensure the request was successful

                string responseBody = await response.Content.ReadAsStringAsync();
                var res = JsonConvert.DeserializeObject<GetAccessTokenResponse>(responseBody);
                return res;
            }
        }
        catch (HttpRequestException ex)
        {
            // Handle exceptions or log errors
            Console.WriteLine($"Error: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// 获取userInfo
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    [ApiDescriptionSettings(Name = "GetUserInfo")]
    public async Task<DingUserInfo> GetUserInfo(GetUserInfoInputDto input)
    {
        string apiUrl = "https://oapi.dingtalk.com/topapi/v2/user/getuserinfo";
        string code = input.code;
        string accessToken = input.access_token; // 替换为实际的访问令牌

        string requestUrl = $"{apiUrl}?code={code}&access_token={accessToken}";

        using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(requestUrl);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
                var res = JsonConvert.DeserializeObject<DingUserInfoRespone>(responseBody);
                return res.result;
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
            }
        }
        return null;
    }

    /// <summary>
    /// 获取手机号码
    /// </summary>
    /// <param name="input"></param>
    /// <returns></retur
    /// ns>
    [HttpPost]
    [AllowAnonymous]
    [ApiDescriptionSettings(Name = "GetUser")]
    public async Task<DingUser> GetUser(GetUserInputDto input)
    {
        try
        {
            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                string apiUrl = "https://oapi.dingtalk.com/topapi/v2/user/get";
                string userId = input.userid;
                string language = "zh_CN";
                string accessToken = input.access_token; // Replace with your actual access token

                string requestUrl = $"{apiUrl}?userid={userId}&language={language}&access_token={accessToken}";

                HttpResponseMessage response = await client.GetAsync(requestUrl);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                    var res = JsonConvert.DeserializeObject<DingUserRespone>(responseBody);
                    return res.result;
                }
                else
                {
                    Console.WriteLine($"Error: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }
        return null;
    }

    /// <summary>
    /// 获取userid
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    [ApiDescriptionSettings(Name = "GetUserId")]
    public async Task<string> GetUserId(GetUserIdInputDto input)
    {
        GetAccessTokenResponse getAccessTokenResponse = await GetAccessTokenAsync();
        var access_token = getAccessTokenResponse.access_token;
        var code = input.code;
        DingUserInfo dingUser = await GetUserInfo(new GetUserInfoInputDto { code=code,access_token=access_token});
        return dingUser.userid;
    }
    public async Task<string> GetUserIdByMobile(string access_token, string tel)
    {
        IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.Mobile = tel;
        OapiV2UserGetbymobileResponse rsp = client.Execute(req, access_token);
        Console.WriteLine(rsp.Body);
        var userId = rsp.Result.Userid;
        return userId;
    }

    public async Task SendMessage(string access_token,string tel,string msg)
    {
        try
        {
            var userId =await  GetUserIdByMobile(access_token, tel);

            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.AgentId = long.Parse(_topSdkOptions.AgentId);
            req.UseridList = userId;
            OapiMessageCorpconversationAsyncsendV2Request.MsgDomain obj1 = new OapiMessageCorpconversationAsyncsendV2Request.MsgDomain();
            obj1.Msgtype = "text";
            OapiMessageCorpconversationAsyncsendV2Request.TextDomain obj2 = new OapiMessageCorpconversationAsyncsendV2Request.TextDomain();
            obj2.Content = msg;
            obj1.Text = obj2;
            req.Msg_ = obj1;
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.Execute(req, access_token);
            Console.WriteLine(rsp.Body);
        }
        catch (Exception ex)
        {
            // 处理异常
            Console.WriteLine(ex.Message);
        }
    }

}
